/*
 *    Copyright (c) 2018-2025, daoism All rights reserved.
 *
 * Redistribution and use in source and binary forms, with or without
 * modification, are permitted provided that the following conditions are met:
 *
 * Redistributions of source code must retain the above copyright notice,
 * this list of conditions and the following disclaimer.
 * Redistributions in binary form must reproduce the above copyright
 * notice, this list of conditions and the following disclaimer in the
 * documentation and/or other materials provided with the distribution.
 * Neither the name of the pig4cloud.com developer nor the names of its
 * contributors may be used to endorse or promote products derived from
 * this software without specific prior written permission.
 * Author: daoism
 */
package com.mkh.st.admin.service.impl;


import cn.hutool.core.bean.BeanUtil;
import cn.hutool.core.collection.CollectionUtil;
import cn.hutool.core.convert.Convert;
import cn.hutool.core.util.BooleanUtil;
import cn.hutool.core.util.ObjectUtil;
import cn.hutool.core.util.RandomUtil;
import cn.hutool.core.util.StrUtil;
import com.baomidou.mybatisplus.core.metadata.IPage;
import com.baomidou.mybatisplus.core.toolkit.Wrappers;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.mkh.st.admin.api.dto.CompanyPageDTO;
import com.mkh.st.admin.api.dto.CompanySaveDTO;
import com.mkh.st.admin.api.dto.SysCompanyIdDTO;
import com.mkh.st.admin.api.entity.SysCompanyInfo;
import com.mkh.st.admin.api.entity.SysMenu;
import com.mkh.st.admin.api.entity.SysRoleMenu;
import com.mkh.st.admin.api.entity.SysUserRoleScope;
import com.mkh.st.admin.api.vo.CompanyDetailVO;
import com.mkh.st.admin.api.vo.CompanyPageVO;
import com.mkh.st.admin.api.vo.DataPermissionVO;
import com.mkh.st.admin.api.vo.SelectCompanyVO;
import com.mkh.st.admin.mapper.SysCompanyInfoMapper;
import com.mkh.st.admin.mapper.SysMenuMapper;
import com.mkh.st.admin.mapper.SysRoleMenuMapper;
import com.mkh.st.admin.mapper.SysUserRoleScopeMapper;
import com.mkh.st.admin.service.SysCompanyInfoService;
import com.mkh.st.admin.service.SysUserService;
import com.mkh.st.common.core.constant.CommonConstants;
import com.mkh.st.common.core.constant.enums.DataStatusEnum;
import com.mkh.st.common.core.constant.enums.MenuEnum;
import com.mkh.st.common.core.constant.enums.ResultCodeEnum;
import com.mkh.st.common.core.constant.enums.ScopeEnum;
import com.mkh.st.common.core.exception.BizException;
import com.mkh.st.common.security.service.DaoismUser;
import com.mkh.st.common.security.util.SecurityUtils;
import lombok.AllArgsConstructor;
import org.springframework.stereotype.Service;
import java.time.LocalDateTime;
import java.util.ArrayList;
import java.util.Arrays;
import java.util.List;
import java.util.stream.Collectors;

/**
 * 公司信息表
 *
 * @author daoism code generator
 * @date 2021-07-06 09:36:04
 */
@Service
@AllArgsConstructor
public class SysCompanyInfoServiceImpl extends ServiceImpl<SysCompanyInfoMapper, SysCompanyInfo> implements SysCompanyInfoService {

	private final SysCompanyInfoMapper sysCompanyInfoMapper;

	private final SysMenuMapper sysMenuMapper;

	private final SysUserRoleScopeMapper sysUserRoleScopeMapper;

	private final SysRoleMenuMapper sysRoleMenuMapper;

	private final SysUserService sysUserService;

	private final List<Long> companyScopeIds= Arrays.asList(ScopeEnum.COMPANY.getId());

    @Override
    public IPage<CompanyPageVO> getSysCompanyInfoPage(Page page, CompanyPageDTO dto) {
		DataPermissionVO dataPermissionVO=sysUserService.getDataPermisston(CommonConstants.ZERO,MenuEnum.BASE_ORGANIZATION_COMPANY.getCode(),companyScopeIds);
		IPage<SysCompanyInfo> iPage=sysCompanyInfoMapper.selectPage(page, Wrappers.<SysCompanyInfo>lambdaQuery()
				.eq(SysCompanyInfo::getDelFlag, CommonConstants.NOT_DEL)
				.eq(SysCompanyInfo::getTenantId,dto.getTenantId())
				.in(BooleanUtil.isFalse(dataPermissionVO.getCompanyAll()),SysCompanyInfo::getCompanyId,dataPermissionVO.getCompanyList())
				.like(StrUtil.isNotBlank(dto.getCompanyName()),SysCompanyInfo::getCompanyName,dto.getCompanyName())
				.like(StrUtil.isNotBlank(dto.getCompanyCode()),SysCompanyInfo::getCompanyCode,dto.getCompanyCode())
				.eq(ObjectUtil.isNotNull(dto.getStatus()),SysCompanyInfo::getStatus,dto.getStatus())
				.orderByDesc(SysCompanyInfo::getCompanyId));
		IPage<CompanyPageVO> iPageInfo=new Page<>();
		if(CollectionUtil.isEmpty(iPage.getRecords())){
			return iPageInfo;
		}
		List<CompanyPageVO> list=new ArrayList<>();
		iPage.getRecords().forEach(entity -> {
			CompanyPageVO vo = BeanUtil.toBean(entity, CompanyPageVO.class);
			vo.setStatusName(DataStatusEnum.get(entity.getStatus()).getDescription());
			list.add(vo);
		});
		iPageInfo.setRecords(list).setTotal(iPage.getTotal()).setSize(iPage.getSize()).setCurrent(iPage.getCurrent()).setPages(iPage.getPages());
		return iPageInfo;
    }

	@Override
	public CompanyDetailVO getCompanyDetail(Long companyId) {
		SysCompanyInfo sysCompanyInfo=sysCompanyInfoMapper.selectById(companyId);
		CompanyDetailVO vo = BeanUtil.toBean(sysCompanyInfo, CompanyDetailVO.class);
		if(StrUtil.isNotBlank(sysCompanyInfo.getArea())){
			vo.setProvince(Convert.toList(Long.class, StrUtil.split(sysCompanyInfo.getArea(),',')));
		}
		return vo;
	}

	@Override
	public Boolean saveCompanyInfo(CompanySaveDTO dto) {
		SysCompanyInfo sysCompanyInfo=BeanUtil.toBean(dto,SysCompanyInfo.class);
		sysCompanyInfo.setArea(CollectionUtil.join(dto.getProvince(),","));
		DaoismUser user = SecurityUtils.getUser();
		if(ObjectUtil.isNotNull(dto.getCompanyId())){//编辑
			//查询公司名称是否存在
			Integer exist= sysCompanyInfoMapper.selectCount(Wrappers.<SysCompanyInfo>lambdaQuery()
				.eq(SysCompanyInfo::getCompanyName,dto.getCompanyName()).eq(SysCompanyInfo::getTenantId,user.getTenantId())
				.eq(SysCompanyInfo::getDelFlag,CommonConstants.NOT_DEL).ne(SysCompanyInfo::getCompanyId,dto.getCompanyId()));
			if(exist>CommonConstants.ZERO){
				throw new BizException(ResultCodeEnum.COMPANY_NAME_EXIST);
			}
			Integer existCode= sysCompanyInfoMapper.selectCount(Wrappers.<SysCompanyInfo>lambdaQuery()
					.eq(SysCompanyInfo::getCompanyCode,dto.getCompanyCode()).eq(SysCompanyInfo::getTenantId,user.getTenantId())
					.eq(SysCompanyInfo::getDelFlag,CommonConstants.NOT_DEL).ne(SysCompanyInfo::getCompanyId,dto.getCompanyId()));
			if(existCode>CommonConstants.ZERO){
				throw new BizException(100,"公司编码已存在!");
			}
			sysCompanyInfo.setUpdatedBy(user.getName()).setUpdateId(user.getId()).setUpdateTime(LocalDateTime.now());
			if(!updateById(sysCompanyInfo)){
				throw new BizException(ResultCodeEnum.SAVE_COMPANY_FAIL);
			}
		}else {
			//查询公司名称是否存在
			Integer exist= sysCompanyInfoMapper.selectCount(Wrappers.<SysCompanyInfo>lambdaQuery().eq(SysCompanyInfo::getCompanyName,dto.getCompanyName())
					.eq(SysCompanyInfo::getDelFlag,CommonConstants.NOT_DEL).eq(SysCompanyInfo::getTenantId,user.getTenantId()));
			if(exist>CommonConstants.ZERO){
				throw new BizException(ResultCodeEnum.COMPANY_NAME_EXIST);
			}
			Integer existCode= sysCompanyInfoMapper.selectCount(Wrappers.<SysCompanyInfo>lambdaQuery()
					.eq(SysCompanyInfo::getCompanyCode,dto.getCompanyCode()).eq(SysCompanyInfo::getTenantId,user.getTenantId())
					.eq(SysCompanyInfo::getDelFlag,CommonConstants.NOT_DEL));
			if(existCode>CommonConstants.ZERO){
				throw new BizException(100,"公司编码已存在!");
			}
			sysCompanyInfo.setCreateId(user.getId()).setUpdatedBy(user.getName())
					.setCreateTime(LocalDateTime.now()).setTenantId(user.getTenantId()).setDelFlag(CommonConstants.NOT_DEL);
			if(!save(sysCompanyInfo)){
				throw new BizException(ResultCodeEnum.SAVE_COMPANY_FAIL);
			}
			//新增的公司加入数据权限
			List<Long> roles = SecurityUtils.getRoles();
			//查询哪个角色公司设置的权限
			SysMenu sysMenu=sysMenuMapper.selectOne(Wrappers.<SysMenu>lambdaQuery().eq(SysMenu::getPermission, MenuEnum.BASE_ORGANIZATION_COMPANY.getCode()));
			roles.forEach(item ->{
				SysRoleMenu sysRoleMenu=sysRoleMenuMapper.selectOne(Wrappers.<SysRoleMenu>lambdaQuery()
						.eq(SysRoleMenu::getRoleId,item).eq(SysRoleMenu::getMenuId,sysMenu.getMenuId()));
				if(ObjectUtil.isNotNull(sysRoleMenu)){
					SysUserRoleScope scope = sysUserRoleScopeMapper.selectOne(Wrappers.<SysUserRoleScope>lambdaQuery()
						.eq(SysUserRoleScope::getRoleId,item).eq(SysUserRoleScope::getUserId,user.getId())
						.eq(SysUserRoleScope::getScopeId, ScopeEnum.COMPANY.getId()));
					if(CommonConstants.ZERO== scope.getAllFlag()){
						scope.setIds(scope.getIds()+","+sysCompanyInfo.getCompanyId());
						if(sysUserRoleScopeMapper.updateById(scope)==CommonConstants.ZERO){
							throw new BizException(ResultCodeEnum.SAVE_COMPANY_FAIL);
						}
					}
				}
			});
		}
		return Boolean.TRUE;
	}

	@Override
	public List<SelectCompanyVO> getSysCompanyInfoList(CompanyPageDTO dto) {
		DataPermissionVO dataPermissionVO=sysUserService.getDataPermisston(CommonConstants.ZERO,MenuEnum.BASE_ORGANIZATION_BUSINESS.getCode(),companyScopeIds);
		List<SysCompanyInfo> companyList=sysCompanyInfoMapper.selectList(Wrappers.<SysCompanyInfo>lambdaQuery()
				.eq(SysCompanyInfo::getDelFlag, CommonConstants.NOT_DEL)
				.eq(SysCompanyInfo::getTenantId,dto.getTenantId())
				.in(BooleanUtil.isFalse(dataPermissionVO.getCompanyAll()),SysCompanyInfo::getCompanyId,dataPermissionVO.getCompanyList())
				.like(StrUtil.isNotBlank(dto.getCompanyName()),SysCompanyInfo::getCompanyName,dto.getCompanyName())
				.like(StrUtil.isNotBlank(dto.getCompanyCode()),SysCompanyInfo::getCompanyCode,dto.getCompanyCode())
				.orderByDesc(SysCompanyInfo::getCompanyId));
		List<SelectCompanyVO> list=new ArrayList<>();
		if(CollectionUtil.isNotEmpty(companyList)){
			list=companyList.stream().map(v ->BeanUtil.toBean(v,SelectCompanyVO.class)).collect(Collectors.toList());
		}
		return list;
	}

	@Override
	public List<SelectCompanyVO> companyInfoList(String menuCode) {
		DataPermissionVO dataPermissionVO=sysUserService.getDataPermisston(CommonConstants.ONE,menuCode,companyScopeIds);
		List<SysCompanyInfo> companyList=sysCompanyInfoMapper.selectList(Wrappers.<SysCompanyInfo>lambdaQuery()
				.eq(SysCompanyInfo::getDelFlag, CommonConstants.NOT_DEL)
				.eq(SysCompanyInfo::getTenantId,SecurityUtils.getUser().getTenantId())
				.in(!dataPermissionVO.getCompanyAll(),SysCompanyInfo::getCompanyId,dataPermissionVO.getCompanyList())
				.orderByDesc(SysCompanyInfo::getCompanyId));
		List<SelectCompanyVO> list=new ArrayList<>();
		if(CollectionUtil.isNotEmpty(companyList)){
			list=companyList.stream().map(v ->BeanUtil.toBean(v,SelectCompanyVO.class)).collect(Collectors.toList());
		}
		return list;
	}

    @Override
    public List<SysCompanyInfo> getCompanyList(SysCompanyIdDTO dto) {
		List<SysCompanyInfo> list = sysCompanyInfoMapper.selectBatchIds(dto.getIds());
		return list;
    }

    @Override
    public SelectCompanyVO getCompanyInfoByName(String name) {
		SysCompanyInfo sysCompanyInfo=sysCompanyInfoMapper.selectOne(Wrappers.<SysCompanyInfo>lambdaQuery()
			.eq(SysCompanyInfo::getDelFlag,CommonConstants.ZERO)
			.eq(SysCompanyInfo::getTenantId,SecurityUtils.getUser().getTenantId())
			.eq(SysCompanyInfo::getCompanyName,name));
		if(ObjectUtil.isNotNull(sysCompanyInfo)){
			return BeanUtil.toBean(sysCompanyInfo,SelectCompanyVO.class);
		}
		return null;
    }

	@Override
	public SelectCompanyVO getCompanyInfoById(Long companyId) {
		return BeanUtil.toBean(sysCompanyInfoMapper.selectById(companyId),SelectCompanyVO.class);
	}
}
